<?php

namespace app\controller;

use app\BaseController;
use Exception;
use think\facade\Filesystem;
use think\response\Json;
class Uploader extends BaseController
{
    /**
     * @return Json
     */
    public function index():Json
    {
        try {
            $file = request()->file('file');
            //格式校验
            $this->validateMimeType($file);
            // 上传到OSS
            $saveName = (new Filesystem)->putFile('upload', $file);
            // 获取完整访问URL
            $host= $this->request->server('HTTP_HOST');
            $fileName = str_replace('\\', '/', $saveName);
            $result = [
                'url' => "https://$host/storage/$fileName",
                'save_name' => $fileName
            ];
            return apiResponse(200, '文件上传成功', $result);
        } catch (Exception $e) {
            return apiResponse($e->getCode(),$e->getMessage());
        }
    }

    /**
     * @param $file
     * @return Exception|void
     */
    protected function validateMimeType($file)
    {
        $mimeType = $file->getMime();
        $allowedMimes = [
            'image/jpeg',
            'image/jpg',
            'image/png',
            'image/gif',
            'image/svg+xml', // SVG格式支持
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
            'application/vnd.ms-excel', // .xls
            'application/msword', // .doc
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
            'application/vnd.ms-powerpoint', // .ppt
            /** @lang text */
            'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
            'application/zip', // .zip
            'application/x-rar-compressed', // .rar
            'application/x-tar', // .tar
            'application/gzip', // .gz
            'application/x-gzip', // .tar.gz

        ];
        if (!in_array($mimeType, $allowedMimes)) {
            return new Exception("上传文件格式不支持");
        }
    }
}